const mongoose = require('mongoose');
var News = require('../models/news.model');  //引数据模型

//获取单个数据
exports.get = function(req,res,next){
	var id = req.params.id;
	// console.log(id);
	News.findById(id,function(err,result){
		// console.log(result);
		res.json(result);
	})
}

//新增
exports.create = function(req,res,next){
	var news = new News(req.body);
	
	news.save()
	.then(data=>{
		res.json(data);
	})
}

//修改
exports.update = function(req,res,next){
	var id = req.params.id;  //req.param('id')
	//现在操作的都是mongoose而不是mongodb
	News.findByIdAndUpdate(id,{$set:req.body},{new:false})
	.then(data=>{  
		res.json({msg:'数据修改成功',status:200});  //如果你要返回数据，这个data返回的是你之前修改的那个数据内容
	})
}

//删除
exports.remove = function(req,res,next){
	var id = req.params.id;
	News.findByIdAndRemove(id,function(err,doc){
		if(err){
			res.json({msg:'数据删除失败',status:404})
		}else{
			res.json({msg:'数据删除成功',status:200})
		}
	});
}

exports.list = function(req,res,next){
	var page = (req.body.page) ? req.body.page : 1;
	var limit = (req.body.limit) ? req.body.limit : 6;
	
	var queryCondition = {};
	var title;
	if(req.body.title && req.body.title.trim().length > 0){
		title = req.body.title;
		queryCondition = {"title":new RegExp(title,'i')}
	}
	
	if(req.body.cateId && req.body.cateId.trim().length > 0){
		cateId = req.body.cateId;
		queryCondition = {"cateId":cateId}
		// queryCondition = Object.assign(queryCondition,{
		// 	"cateId":cateId
		// })
		// //Object.assign是一个对象合并的操作
		// {
		// 	{"title":new RegExp(title,'i')},
		// 	{"cateId":cateId}
		// }
	}
	
	News.paginate(queryCondition,{page:page,limit:limit},function(err,result){
		result.rows = result.docs;
		delete result.docs;
		res.json(result);
	});
}
